<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>爱情动态</title>
    <script src="/Style/js/tailwindcss.js"></script>
    <link href="/Style/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#ec4899',    // 主题粉色
                        secondary: '#fce7f3',  // 浅粉色背景
                        partner: '#3b82f6',    // 伴侣方蓝色
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .post-card {
                @apply bg-white rounded-xl shadow-sm p-4 mb-4 transition-all hover:shadow-md;
            }
            .timeline-divider {
                @apply my-6 relative flex items-center justify-center;
            }
            .timeline-divider span {
                @apply bg-secondary text-primary px-4 py-1 rounded-full text-sm font-medium relative z-10;
            }
            .timeline-divider::after {
                @apply content-[''] absolute top-1/2 left-0 right-0 h-0.5 bg-gray-200 -z-0;
            }
            .own-post {
                @apply border-l-4 border-primary;
            }
            .partner-post {
                @apply border-l-4 border-partner;
            }
            .post-image-container {
                @apply overflow-hidden rounded-lg my-2;
            }
            .post-image {
                @apply w-full object-cover transition-transform duration-300 hover:scale-105;
            }
            .btn-disabled {
                @apply opacity-50 cursor-not-allowed pointer-events-none;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans">
<!-- 导航栏 -->
<nav class="bg-white shadow-md fixed w-full top-0 z-50">
    <div class="container mx-auto px-4 py-3">
        <div class="flex justify-between items-center">
            <div class="flex items-center">
                <i class="fa fa-heart text-primary text-2xl mr-2"></i>
                <span class="text-xl font-bold text-gray-800">我们的点点滴滴</span>
            </div>

            <div class="hidden md:flex space-x-8">
                <a href="/" class="text-dark hover:text-primary transition-colors py-2">首页</a>
                <a href="/moments" class="text-primary border-b-2 border-primary font-medium py-2">点点滴滴</a>
                <a href="/photos" class="text-dark hover:text-primary transition-colors py-2">Love Photo</a>
                <a href="/lovelist" class="text-dark hover:text-primary transition-colors py-2">Love List</a>
                <a href="/messages" class="text-dark hover:text-primary transition-colors py-2">留言板</a>
                <a href="/couple" class="text-dark hover:text-primary transition-colors py-2">爱情纪念</a>
            </div>

            <div class="flex items-center space-x-4">
                <div class="relative">
                    <button id="user-menu-button" class="flex items-center space-x-2 focus:outline-none">
                        <img id="user-menu-touxiang"
                             src="{{ session.avatar if session.avatar else '/default_avatar.jpg' }}"
                             alt="用户头像" class="w-8 h-8 rounded-full object-cover border-2 border-primary"
                             onerror="this.src='https://picsum.photos/200/200?random=1'">
                        <span class="hidden md:inline text-gray-700">{{ session.nickname }}</span>
                        <i class="fa fa-chevron-down text-xs text-gray-500"></i>
                    </button>
                    <div id="user-menu"
                         class="hidden absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-10">
                        <a href="#" id="open-profile" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">个人资料</a>
                        <a href="/logout" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">退出登录</a>
                    </div>
                </div>
                <button id="mobile-menu-button" class="md:hidden text-gray-700">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </div>

        <!-- 移动端菜单 -->
        <div id="mobile-menu" class="hidden md:hidden mt-4 pb-2">
            <a href="/" class="block text-dark hover:text-primary transition-colors py-2">首页</a>
            <a href="/moments" class="block text-primary font-medium py-2">点点滴滴</a>
            <a href="/photos" class="block text-dark hover:text-primary transition-colors py-2">Love Photo</a>
            <a href="/lovelist" class="block text-dark hover:text-primary transition-colors py-2">Love List</a>
            <a href="/messages" class="block text-dark hover:text-primary transition-colors py-2">留言板</a>
            <a href="/couple" class="block text-dark hover:text-primary transition-colors py-2">爱情纪念</a>
        </div>
    </div>
</nav>

<!-- 主内容 -->
<main class="container mx-auto px-4 pt-24 pb-16">
    <!-- 发布动态区域 -->
    <div class="bg-white rounded-xl shadow-md p-6 mb-8">
        <h2 class="text-xl font-semibold text-gray-800 mb-4">分享我们的点滴</h2>
        <form id="postForm">
            <div class="mb-4">
                <textarea id="postContent" rows="3"
                          class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent resize-none"
                          placeholder="分享你的心情、照片或故事..."></textarea>
            </div>
            <div class="mb-4">
				<label for="postImage" class="block text-gray-700 mb-2 flex items-center gap-2 cursor-pointer group">
					<i class="fa fa-cloud-upload text-primary transition-transform group-hover:scale-110"></i>
					<span class="font-medium">上传图片（可选）</span>
				</label>
				
				<div class="relative">
					<input type="file" id="postImage" accept="image/*"
						   class="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10">
					<!-- 视觉替代按钮 -->
					<div class="w-full px-6 py-4 border-2 border-dashed border-gray-300 rounded-lg text-center transition-all hover:border-primary hover:bg-gray-50">
						<i class="fa fa-image text-3xl text-gray-400 mb-2"></i>
						<p class="text-gray-600">点击或拖拽选择图片</p>
					</div>
				</div>
				
				<div id="imagePreview" class="mt-4 flex flex-wrap gap-3">
				</div>
			</div>
            <button type="submit" id="postSubmitBtn"
                    class="bg-primary hover:bg-primary/90 text-white font-medium py-3 px-6 rounded-lg transition-colors flex items-center">
                <i class="fa fa-paper-plane mr-2"></i>发布动态
            </button>
        </form>
    </div>

    <!-- 动态时间线容器 -->
    <div id="postsContainer" class="mb-8">
        <!-- 加载状态 -->
        <div class="text-center py-12" id="loadingState">
            <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary mb-4"></div>
            <p class="text-gray-500">加载动态中...</p>
        </div>

        <!-- 空状态 -->
        <div id="emptyState" class="text-center py-12 hidden">
            <div class="w-20 h-20 bg-secondary rounded-full flex items-center justify-center mx-auto mb-4">
                <i class="fa fa-camera text-primary text-3xl"></i>
            </div>
            <p class="text-gray-600 mb-4">还没有动态呢</p>
            <p class="text-gray-500">发布你们的第一条动态，记录美好瞬间吧~</p>
        </div>
    </div>

    <!-- 加载更多 -->
    <div class="text-center mb-8">
        <button id="loadMoreBtn" class="px-6 py-3 bg-white border border-primary text-primary rounded-lg hover:bg-secondary transition-colors hidden">
            <i class="fa fa-refresh mr-2"></i>加载更多
        </button>
        <div id="loadingMore" class="hidden">
            <div class="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
            <p class="text-gray-500 mt-2">加载中...</p>
        </div>
    </div>
</main>

<!-- 编辑动态模态框 -->
<div id="editModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-lg w-full max-w-lg mx-4 p-6 transform transition-all">
        <h3 class="text-xl font-bold text-gray-800 mb-4">编辑动态</h3>

        <input type="hidden" id="editPostId">
        <input type="hidden" id="editPostImage">

        <div class="mb-6">
            <label for="editContent" class="block text-gray-700 mb-2">动态内容</label>
            <textarea id="editContent" rows="4"
                      class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent resize-none"
                      placeholder="输入动态内容..."></textarea>
        </div>

        <div class="mb-6">
            <img id="editImagePreview" src="" alt="预览图" class="max-w-full h-48 object-cover rounded-lg hidden">
        </div>

        <div class="flex justify-end space-x-3">
            <button id="cancelEdit"
                    class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                取消
            </button>
            <button id="saveEdit"
                    class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                保存修改
            </button>
        </div>
    </div>
</div>

<!-- 确认删除模态框 -->
<div id="deleteModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-lg w-full max-w-md mx-4 p-6">
        <h3 class="text-xl font-bold text-gray-800 mb-4">确认删除</h3>
        <p class="text-gray-600 mb-6">确定要删除这条动态吗？此操作不可撤销。</p>

        <input type="hidden" id="deletePostId">

        <div class="flex justify-end space-x-3">
            <button id="cancelDelete"
                    class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                取消
            </button>
            <button id="confirmDelete"
                    class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors">
                确认删除
            </button>
        </div>
    </div>
</div>


<!-- 评论模态框 -->
<div id="commentModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-lg w-full max-w-lg mx-4 p-6 transform transition-all max-h-[80vh] overflow-hidden flex flex-col">
        <!-- 固定的头部区域 -->
        <div class="flex justify-between items-center mb-4 flex-shrink-0">
            <h3 class="text-xl font-bold text-gray-800">评论</h3>
            <button id="closeCommentModal" class="text-gray-500 hover:text-gray-700 transition-colors p-1 rounded-full hover:bg-gray-100">
                <i class="fa fa-times text-xl"></i>
            </button>
        </div>

        <!-- 可滚动的内容区域 -->
        <div class="flex-grow overflow-y-auto">
            <input type="hidden" id="commentPostId">

            <div class="mb-4">
                <textarea id="commentContent" rows="3"
                          class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent resize-none"
                          placeholder="添加评论..."></textarea>
            </div>

            <button id="sendComment"
                    class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-3 rounded-lg transition-colors flex items-center justify-center mb-6">
                <i class="fa fa-comment mr-2"></i>发送评论
            </button>

            <div id="commentsList" class="space-y-4">
                <!-- 评论列表将动态加载 -->
            </div>
        </div>
    </div>
</div>

<!-- 通知提示 -->
<div id="notification"
     class="fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50">
    <i id="notificationIcon" class="mr-2"></i>
    <span id="notificationMessage"></span>
</div>

<script>
// 全局变量
let currentUser = null;
let partnerInfo = null;
let inRelationship = false;
let currentPage = 1;
let hasMore = true;
let lastDate = null;
let isLoading = false;


function throttle(fn, delay = 100) {
  let lastTime = 0;
  return function(...args) {
    const now = Date.now();
    if (now - lastTime > delay) {
      fn.apply(this, args);
      lastTime = now;
    }
  };
}

// 页面初始化
document.addEventListener('DOMContentLoaded', () => {
    checkLoginStatus();
    bindEvents();
});



// 检查登录状态并加载动态
function checkLoginStatus() {
    fetch('/api/user')
        .then(res => {
            if (!res.ok) throw new Error('未登录');
            return res.json();
        })
        .then(user => {
            currentUser = user;
            Promise.all([loadRelationshipStatus(), loadPosts(1)])
                .catch(err => console.error('初始化失败:', err));
        })
        .catch(error => {
            console.error('登录状态异常:', error);
            window.location.href = '/login';
        });
}

// 加载情侣关系状态
function loadRelationshipStatus() {
    return fetch('/api/couple/relationship')
        .then(res => res.json())
        .then(data => {
            inRelationship = data.in_relationship;
            partnerInfo = data.partner || null;
            return data;
        });
}

// 加载动态
function loadPosts(page) {
    if (isLoading || !hasMore) return Promise.resolve();

    isLoading = true;
    const container = document.getElementById('postsContainer');
    const loadMoreBtn = document.getElementById('loadMoreBtn');
    const loadingMore = document.getElementById('loadingMore');

    // 显示加载状态
    if (page === 1) {
        container.querySelector('#loadingState').classList.remove('hidden');
        container.querySelector('#emptyState').classList.add('hidden');
    } else {
        loadMoreBtn.classList.add('hidden');
        loadingMore.classList.remove('hidden');
    }

    return fetch(`/api/posts?page=${page}&per_page=10`)
        .then(res => {
            if (!res.ok) throw new Error('加载动态失败');
            return res.json();
        })
        .then(data => {
            currentPage = page;
            hasMore = data.pagination?.has_next || false;

            // 处理数据
            const posts = data.posts || [];
            const container = document.getElementById('postsContainer');

            // 首次加载清空容器
            if (page === 1) {
                container.innerHTML = `
                    <div id="loadingState" class="text-center py-12 hidden">
                        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary mb-4"></div>
                        <p class="text-gray-500">加载动态中...</p>
                    </div>
                    <div id="emptyState" class="text-center py-12 hidden">
                        <div class="w-20 h-20 bg-secondary rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fa fa-camera text-primary text-3xl"></i>
                        </div>
                        <p class="text-gray-600 mb-4">还没有动态呢</p>
                        <p class="text-gray-500">发布你们的第一条动态，记录美好瞬间吧~</p>
                    </div>
                `;
                lastDate = null;
            }

            // 添加动态
            addPostsToContainer(container, posts); 

            // 处理空状态
            if (currentPage === 1 && posts.length === 0) {
                container.querySelector('#loadingState').classList.add('hidden');
                container.querySelector('#emptyState').classList.remove('hidden');
            } else {
                container.querySelector('#loadingState').classList.add('hidden');
            }

            // 控制加载更多按钮
            if (hasMore) {
                loadMoreBtn.classList.remove('hidden');
                loadingMore.classList.add('hidden');
            } else {
                loadMoreBtn.classList.add('hidden');
                loadingMore.classList.add('hidden');
            }

            isLoading = false;
            return data;
        })
        .catch(error => {
            console.error('加载动态失败:', error);
            showNotification('加载动态失败', 'error');
            isLoading = false;

            // 恢复按钮状态
            if (page > 1) {
                loadMoreBtn.classList.remove('hidden');
                loadingMore.classList.add('hidden');
            }
        });
}

// 添加动态到容器
function addPostsToContainer(container, posts) {
  const fragment = document.createDocumentFragment(); // 文档片段，临时存储元素
  let lastDate = null;

  posts.forEach(post => {
    // 处理时间线分割线
    const postDate = new Date(post.created_at);
    const dateStr = postDate.toLocaleDateString();
    if (dateStr !== lastDate) {
      const divider = document.createElement('div');
      divider.className = 'timeline-divider';
      divider.innerHTML = `<span>${dateStr}</span>`;
      fragment.appendChild(divider);
      lastDate = dateStr;
    }

    // 创建动态元素并添加到片段
    const postElement = createPostElement(post);
    fragment.appendChild(postElement);
  });

  // 一次性添加到页面
  container.appendChild(fragment);
}


// 创建动态元素
function createPostElement(post) {
    const div = document.createElement('div');

    // 对于情侣关系，使用分栏布局
    let columnClass = 'mb-4';
    let postBorderClass = '';

    if (inRelationship) {
        // 自己的动态在左边，伴侣的在右边
        columnClass = post.is_own ? 'mb-4 md:ml-0 md:mr-auto md:w-5/12' : 'mb-4 md:ml-auto md:mr-0 md:w-5/12';
        postBorderClass = post.is_own ? 'own-post' : 'partner-post';
    }

    div.className = columnClass;

    // 图片容器和样式优化
    let imageHtml = '';
    if (post.image_url) {
        imageHtml = `
            <div class="post-image-container">
                <img src="${post.image_url}" class="post-image" alt="动态图片" onload="adjustImageHeight(this)">
            </div>
        `;
    }

    div.innerHTML = `
        <div class="post-card ${postBorderClass}">
            <div class="flex justify-between items-start mb-3">
                <div class="flex items-center">
                    <img src="${post.author.avatar || 'https://picsum.photos/200/200?random=1'}"
                         alt="${post.author.nickname}的头像"
                         class="w-10 h-10 rounded-full mr-3 object-cover">
                    <div>
                        <p class="font-medium text-gray-800">${post.author.nickname}</p>
                        <p class="text-xs text-gray-500">${formatTime(post.created_at)}</p>
                    </div>
                </div>

                ${post.is_own ? `
                <div class="relative">
                    <button class="text-gray-500 hover:text-gray-700 focus:outline-none post-actions-btn">
                        <i class="fa fa-ellipsis-h"></i>
                    </button>
                    <div class="hidden absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-10 post-actions-menu">
                        <a href="#" class="edit-post block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" data-id="${post.id}">
                            <i class="fa fa-edit mr-1"></i>编辑
                        </a>
                        <a href="#" class="delete-post block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" data-id="${post.id}">
                            <i class="fa fa-trash mr-1"></i>删除
                        </a>
                    </div>
                </div>` : ''}
            </div>

            <div class="mb-3">
                ${post.content ? `<p class="text-gray-700">${formatMessageContent(post.content)}</p>` : ''}
                ${imageHtml}
            </div>

            <div class="flex justify-between text-sm">
                <button class="text-gray-600 hover:text-primary transition-colors view-comments" data-id="${post.id}">
                    <i class="fa fa-comment-o mr-1"></i>评论 (${post.comment_count || 0})
                </button>
            </div>
        </div>
    `;

    return div;
}

// 根据图片宽高比调整高度
function adjustImageHeight(img) {
    // 限制最大高度为300px，同时保持宽高比
    const maxHeight = 300;
    if (img.height > maxHeight) {
        const ratio = maxHeight / img.height;
        img.style.height = `${maxHeight}px`;
        img.style.width = `${img.width * ratio}px`;
        // 居中显示
        img.style.marginLeft = 'auto';
        img.style.marginRight = 'auto';
    }
}

// 绑定所有事件
function bindEvents() {
    // 用户菜单切换
    const userMenuButton = document.getElementById('user-menu-button');
    const userMenu = document.getElementById('user-menu');
    if (userMenuButton && userMenu) {
        userMenuButton.addEventListener('click', function(e) {
            e.stopPropagation();
            userMenu.classList.toggle('hidden');
        });
    }

    // 移动端菜单切换
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const mobileMenu = document.getElementById('mobile-menu');
    if (mobileMenuButton && mobileMenu) {
        mobileMenuButton.addEventListener('click', function(e) {
            e.stopPropagation();
            mobileMenu.classList.toggle('hidden');
        });
    }

    // 点击其他地方关闭菜单
    document.addEventListener('click', function() {
        const userMenu = document.getElementById('user-menu');
        if (userMenu && !userMenu.classList.contains('hidden')) {
            userMenu.classList.add('hidden');
        }

        const mobileMenu = document.getElementById('mobile-menu');
        if (mobileMenu && !mobileMenu.classList.contains('hidden')) {
            mobileMenu.classList.add('hidden');
        }

        // 关闭所有动态操作菜单
        document.querySelectorAll('.post-actions-menu').forEach(menu => {
            menu.classList.add('hidden');
        });
    });

    // 动态操作菜单
    document.addEventListener('click', function(e) {
        if (e.target.closest('.post-actions-btn')) {
            e.stopPropagation();
            const btn = e.target.closest('.post-actions-btn');
            const menu = btn.nextElementSibling;
            menu.classList.toggle('hidden');
        }
    });

    // 加载更多按钮
    document.getElementById('loadMoreBtn').addEventListener('click', function() {
        loadPosts(currentPage + 1);
    });

    // 发布动态表单
    document.getElementById('postForm').addEventListener('submit', function(e) {
        e.preventDefault();
        submitPost();
    });

    // 图片预览
    document.getElementById('postImage').addEventListener('change', handleImagePreview);

    // 编辑动态
    document.addEventListener('click', function(e) {
        if (e.target.closest('.edit-post')) {
            e.preventDefault();
            const btn = e.target.closest('.edit-post');
            const postId = btn.getAttribute('data-id');
            openEditModal(postId);

            // 关闭操作菜单
            btn.closest('.post-actions-menu').classList.add('hidden');
        }
    });

    // 删除动态
    document.addEventListener('click', function(e) {
        if (e.target.closest('.delete-post')) {
            e.preventDefault();
            const btn = e.target.closest('.delete-post');
            const postId = btn.getAttribute('data-id');
            openDeleteModal(postId);

            // 关闭操作菜单
            btn.closest('.post-actions-menu').classList.add('hidden');
        }
    });

    // 查看评论
    document.addEventListener('click', function(e) {
        if (e.target.closest('.view-comments')) {
            const btn = e.target.closest('.view-comments');
            const postId = btn.getAttribute('data-id');
            openCommentModal(postId);
        }
    });

    // 编辑模态框
    document.getElementById('cancelEdit').addEventListener('click', closeEditModal);
    document.getElementById('saveEdit').addEventListener('click', saveEdit);

    // 删除模态框
    document.getElementById('cancelDelete').addEventListener('click', closeDeleteModal);
    document.getElementById('confirmDelete').addEventListener('click', confirmDelete);

    // 评论模态框
    document.getElementById('closeCommentModal').addEventListener('click', closeCommentModal);
    document.getElementById('sendComment').addEventListener('click', sendComment);

    // 点击模态框外部关闭评论弹窗
    document.getElementById('commentModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeCommentModal();
        }
    });

    // 按ESC键关闭评论弹窗
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const commentModal = document.getElementById('commentModal');
            if (!commentModal.classList.contains('hidden')) {
                closeCommentModal();
            }
        }
    });
}

// 处理图片预览
function handleImagePreview(e) {
    const previewContainer = document.getElementById('imagePreview');
    previewContainer.innerHTML = '';

    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const img = document.createElement('img');
            img.src = e.target.result;
            // 优化预览图大小
            img.className = 'w-32 h-32 object-cover rounded-lg border border-gray-200';
            previewContainer.appendChild(img);
        }
        reader.readAsDataURL(file);
    }
}

// 提交新动态
function submitPost() {
    const content = document.getElementById('postContent').value.trim();
    const imageInput = document.getElementById('postImage');
    const submitBtn = document.getElementById('postSubmitBtn');

    if (!content && imageInput.files.length === 0) {
        showNotification('内容或图片不能为空', 'error');
        return;
    }

    // 禁用按钮并显示加载状态
    submitBtn.disabled = true;
    submitBtn.classList.add('btn-disabled');
    submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>发布中...';

    let imageUrl = '';
    const uploadImagePromise = new Promise((resolve) => {
        if (imageInput.files.length > 0) {
            const formData = new FormData();
            formData.append('file', imageInput.files[0]);

            fetch('/api/upload', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if (data.status === 'success') {
                    imageUrl = data.url;
                } else {
                    showNotification('图片上传失败: ' + (data.message || ''), 'error');
                }
                resolve();
            })
            .catch(error => {
                console.error('图片上传失败:', error);
                showNotification('图片上传失败', 'error');
                resolve();
            });
        } else {
            resolve();
        }
    });

    uploadImagePromise.then(() => {
        if (!content && !imageUrl) {
            // 恢复按钮状态
            submitBtn.disabled = false;
            submitBtn.classList.remove('btn-disabled');
            submitBtn.innerHTML = '<i class="fa fa-paper-plane mr-2"></i>发布动态';
            return;
        }

        fetch('/api/posts', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ content, image_url: imageUrl })
        })
        .then(res => res.json())
        .then(data => {
            if (data.status === 'success') {
                showNotification('动态发布成功', 'success');

                // 获取新发布的动态并添加到顶部
                fetch(`/api/posts/${data.post_id}`)
                    .then(res => res.json())
                    .then(newPost => {
                        const container = document.getElementById('postsContainer');
                        // 清空空状态（如果存在）
                        container.querySelector('#emptyState').classList.add('hidden');

                        // 创建新动态元素
                        const newPostElement = createPostElement(newPost);

                        // 添加时间线分割（如果需要）
                        const postDate = new Date(newPost.created_at);
                        const dateStr = postDate.toLocaleDateString();
                        if (dateStr !== lastDate) {
                            const divider = document.createElement('div');
                            divider.className = 'timeline-divider';
                            divider.innerHTML = `<span>${dateStr}</span>`;
                            container.prepend(divider);
                            lastDate = dateStr;
                        }

                        // 添加到容器顶部
                        container.prepend(newPostElement);
                    });

                // 清空表单
                document.getElementById('postContent').value = '';
                imageInput.value = '';
                document.getElementById('imagePreview').innerHTML = '';
            } else {
                showNotification('发布失败: ' + (data.message || ''), 'error');
            }
        })
        .catch(error => {
            console.error('发布动态失败:', error);
            showNotification('发布动态失败', 'error');
        })
        .finally(() => {
            // 恢复按钮状态
            submitBtn.disabled = false;
            submitBtn.classList.remove('btn-disabled');
            submitBtn.innerHTML = '<i class="fa fa-paper-plane mr-2"></i>发布动态';
        });
    });
}

// 打开编辑模态框
function openEditModal(postId) {
    fetch(`/api/posts/${postId}`)
        .then(res => {
            if (!res.ok) throw new Error('获取动态详情失败');
            return res.json();
        })
        .then(post => {
            document.getElementById('editPostId').value = post.id;
            document.getElementById('editPostImage').value = post.image_url || '';
            document.getElementById('editContent').value = post.content || '';

            const imagePreview = document.getElementById('editImagePreview');
            if (post.image_url) {
                imagePreview.src = post.image_url;
                imagePreview.classList.remove('hidden');
                imagePreview.style.maxHeight = '200px';
                imagePreview.style.objectFit = 'contain';
            } else {
                imagePreview.src = '';
                imagePreview.classList.add('hidden');
            }

            document.getElementById('editModal').classList.remove('hidden');
        })
        .catch(error => {
            console.error('获取动态详情失败:', error);
            showNotification('无法编辑动态', 'error');
        });
}

// 关闭编辑模态框
function closeEditModal() {
    document.getElementById('editModal').classList.add('hidden');
}

// 保存编辑
function saveEdit() {
    const postId = document.getElementById('editPostId').value;
    const content = document.getElementById('editContent').value.trim();
    const saveBtn = document.getElementById('saveEdit');

    if (!postId) {
        showNotification('编辑失败', 'error');
        return;
    }

    // 内容不能为空（如果没有图片）
    const imageUrl = document.getElementById('editPostImage').value;
    if (!content && !imageUrl) {
        showNotification('内容不能为空', 'error');
        return;
    }

    // 禁用按钮并显示加载状态
    saveBtn.disabled = true;
    saveBtn.classList.add('btn-disabled');
    saveBtn.textContent = '保存中...';

    fetch(`/api/posts/${postId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            content: content
        })
    })
    .then(res => res.json())
    .then(data => {
        if (data.status === 'success') {
            showNotification('动态已更新', 'success');
            closeEditModal();
            loadPosts(currentPage);
        } else {
            showNotification('更新失败: ' + (data.message || ''), 'error');
        }
    })
    .catch(error => {
        console.error('更新动态失败:', error);
        showNotification('更新动态失败', 'error');
    })
    .finally(() => {
        // 恢复按钮状态
        saveBtn.disabled = false;
        saveBtn.classList.remove('btn-disabled');
        saveBtn.textContent = '保存修改';
    });
}

// 打开删除模态框
function openDeleteModal(postId) {
    document.getElementById('deletePostId').value = postId;
    document.getElementById('deleteModal').classList.remove('hidden');
}

// 关闭删除模态框
function closeDeleteModal() {
    document.getElementById('deleteModal').classList.add('hidden');
}

// 确认删除
function confirmDelete() {
    const postId = document.getElementById('deletePostId').value;
    const confirmBtn = document.getElementById('confirmDelete');

    if (!postId) {
        showNotification('删除失败', 'error');
        closeDeleteModal();
        return;
    }

    // 禁用按钮并显示加载状态
    confirmBtn.disabled = true;
    confirmBtn.classList.add('btn-disabled');
    confirmBtn.textContent = '删除中...';

    fetch(`/api/posts/${postId}`, {
        method: 'DELETE'
    })
    .then(res => res.json())
    .then(data => {
        if (data.status === 'success') {
            showNotification('动态已删除', 'success');
            closeDeleteModal();
            loadPosts(currentPage);
        } else {
            showNotification('删除失败: ' + (data.message || ''), 'error');
        }
    })
    .catch(error => {
        console.error('删除动态失败:', error);
        showNotification('删除动态失败', 'error');
    })
    .finally(() => {
        // 恢复按钮状态
        confirmBtn.disabled = false;
        confirmBtn.classList.remove('btn-disabled');
        confirmBtn.textContent = '确认删除';
    });
}

// 打开评论模态框
function openCommentModal(postId) {
    document.getElementById('commentPostId').value = postId;
    document.getElementById('commentContent').value = '';

    // 加载评论
    loadComments(postId);

    document.getElementById('commentModal').classList.remove('hidden');
}

// 关闭评论模态框
function closeCommentModal() {
    document.getElementById('commentModal').classList.add('hidden');
    document.getElementById('commentContent').value = ''; // 清空评论内容
}

// 加载评论
function loadComments(postId) {
    const commentsList = document.getElementById('commentsList');
    commentsList.innerHTML = `
        <div class="text-center py-6">
            <div class="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
            <p class="text-gray-500 mt-2">加载评论中...</p>
        </div>
    `;

    // 移除旧事件，避免重复绑定
    commentsList.removeEventListener('click', handleCommentEvents);

    fetch(`/api/posts/${postId}`)
        .then(res => {
            if (!res.ok) throw new Error('获取评论失败');
            return res.json();
        })
        .then(post => {
            commentsList.innerHTML = '';

            if (post.comments.length === 0) {
                commentsList.innerHTML = `
                    <div class="text-center py-6">
                        <p class="text-gray-500">还没有评论，快来抢沙发吧~</p>
                    </div>
                `;
                return;
            }

            // 渲染评论
            post.comments.forEach(comment => {
                const commentEl = createCommentElement(comment);
                commentsList.appendChild(commentEl);
            });

            // 绑定评论相关事件
            commentsList.addEventListener('click', handleCommentEvents);
        })
        .catch(error => {
            console.error('获取评论失败:', error);
            commentsList.innerHTML = `
                <div class="text-center py-6">
                    <p class="text-red-500">加载评论失败</p>
                </div>
            `;
        });
}

// 创建评论元素
function createCommentElement(comment) {
    const div = document.createElement('div');
    div.className = 'comment p-3 bg-gray-50 rounded-lg';

    let repliesHtml = '';
    if (comment.replies && comment.replies.length > 0) {
        repliesHtml = '<div class="mt-2 ml-6 border-l-2 border-gray-200 pl-3 space-y-3">';
        comment.replies.forEach(reply => {
            repliesHtml += `
                <div class="reply">
                    <div class="flex">
                        <img src="${reply.author.avatar || 'https://picsum.photos/200/200?random=2'}"
                             alt="${reply.author.nickname}的头像"
                             class="w-6 h-6 rounded-full mr-2 object-cover">
                        <div class="flex-1">
                            <div class="bg-white p-2 rounded">
                                <span class="font-medium text-sm">${reply.author.nickname}</span>
                                <span class="text-sm ml-1">${formatMessageContent(reply.content)}</span>
                            </div>
                            <div class="flex items-center mt-1">
                                <span class="text-xs text-gray-500">${formatTime(reply.created_at)}</span>
                                ${reply.is_own ? `
                                <button class="delete-comment ml-3 text-xs text-red-500 hover:text-red-600" data-id="${reply.id}">
                                    删除
                                </button>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });
        repliesHtml += '</div>';
    }

    div.innerHTML = `
        <div class="flex">
            <img src="${comment.author.avatar || 'https://picsum.photos/200/200?random=2'}"
                 alt="${comment.author.nickname}的头像"
                 class="w-8 h-8 rounded-full mr-3 object-cover">
            <div class="flex-1">
                <div>
                    <span class="font-medium">${comment.author.nickname}</span>
                    <span class="text-gray-500 text-sm ml-2">${formatTime(comment.created_at)}</span>
                </div>
                <p class="mt-1 text-gray-700">${formatMessageContent(comment.content)}</p>

                <div class="flex items-center mt-2">
                    <button class="reply-to-comment text-sm text-primary hover:text-primary/80" data-id="${comment.id}">
                        <i class="fa fa-reply mr-1"></i>回复
                    </button>
                    ${comment.is_own ? `
                    <button class="delete-comment text-sm text-red-500 hover:text-red-600 ml-4" data-id="${comment.id}">
                        <i class="fa fa-trash mr-1"></i>删除
                    </button>
                    ` : ''}
                </div>

                <!-- 回复输入框 (默认隐藏) -->
                <div class="reply-input mt-2 hidden">
                    <textarea rows="2" class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent resize-none"
                              placeholder="回复 ${comment.author.nickname}..."></textarea>
                    <div class="flex justify-end mt-1">
                        <button class="cancel-reply text-sm px-3 py-1 border border-gray-300 rounded mr-2 hover:bg-gray-100">
                            取消
                        </button>
                        <button class="send-reply text-sm px-3 py-1 bg-primary text-white rounded hover:bg-primary/90" data-comment-id="${comment.id}">
                            发送
                        </button>
                    </div>
                </div>

                <!-- 回复列表 -->
                ${repliesHtml}
            </div>
        </div>
    `;

    return div;
}

// 评论区域事件处理函数（使用事件委托）
function handleCommentEvents(e) {
    const target = e.target.closest('button');
    if (!target) return;

    // 回复按钮点击
    if (target.classList.contains('reply-to-comment')) {
        const commentId = target.getAttribute('data-id');
        const replyInput = target.parentElement.nextElementSibling;

        // 隐藏其他所有回复框
        document.querySelectorAll('.reply-input').forEach(el => {
            if (el !== replyInput) el.classList.add('hidden');
        });

        // 显示当前回复框并聚焦
        replyInput.classList.toggle('hidden');
        if (!replyInput.classList.contains('hidden')) {
            replyInput.querySelector('textarea').focus();
        }
        e.stopPropagation();
    }

    // 取消回复
    else if (target.classList.contains('cancel-reply')) {
        target.closest('.reply-input').classList.add('hidden');
        e.stopPropagation();
    }

    // 发送回复
    else if (target.classList.contains('send-reply')) {
        sendReplyHandler(target);
        e.stopPropagation();
    }

    // 删除评论
    else if (target.classList.contains('delete-comment')) {
        const commentId = target.getAttribute('data-id');
        const postId = document.getElementById('commentPostId').value;

        if (confirm('确定要删除这条评论吗？')) {
            // 禁用按钮并显示加载状态
            target.disabled = true;
            target.classList.add('btn-disabled');
            
            fetch(`/api/comments/${commentId}`, { method: 'DELETE' })
                .then(res => res.json())
                .then(data => {
                    if (data.status === 'success') {
                        showNotification('评论已删除', 'success');
                        loadComments(postId);
                    } else {
                        showNotification('删除失败: ' + (data.message || ''), 'error');
                    }
                })
                .catch(error => {
                    console.error('删除评论失败:', error);
                    showNotification('删除评论失败', 'error');
                })
                .finally(() => {
                    // 恢复按钮状态
                    target.disabled = false;
                    target.classList.remove('btn-disabled');
                });
        }
        e.stopPropagation();
    }
}

// 发送回复处理函数
function sendReplyHandler(btn) {
    const commentId = btn.getAttribute('data-comment-id');
    const replyInput = btn.closest('.reply-input');
    const textarea = replyInput.querySelector('textarea');
    const content = textarea.value.trim();
    const postId = document.getElementById('commentPostId').value;

    if (!content) {
        showNotification('回复内容不能为空', 'error');
        return;
    }

    // 禁用按钮并显示加载状态
    btn.disabled = true;
    btn.classList.add('btn-disabled');
    btn.textContent = '发送中...';

    fetch(`/api/posts/${postId}/comments`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content, parent_id: commentId })
    })
    .then(res => res.json())
    .then(data => {
        if (data.status === 'success') {
            showNotification('回复成功', 'success');
            fetch(`/api/comments/${data.comment_id}`)
                .then(res => res.json())
                .then(newReply => {
                    const commentEl = btn.closest('.comment');
                    let repliesContainer = commentEl.querySelector('.border-l-2');

                    // 没有回复容器则创建
                    if (!repliesContainer) {
                        repliesContainer = document.createElement('div');
                        repliesContainer.className = 'mt-2 ml-6 border-l-2 border-gray-200 pl-3 space-y-3';
                        commentEl.querySelector('.reply-input').after(repliesContainer);
                    }

                    // 添加新回复
                    const replyHtml = `
                        <div class="reply">
                            <div class="flex">
                                <img src="${newReply.author.avatar || 'https://picsum.photos/200/200?random=2'}" class="w-6 h-6 rounded-full mr-2">
                                <div class="flex-1">
                                    <div class="bg-white p-2 rounded">
                                        <span class="font-medium text-sm">${newReply.author.nickname}</span>
                                        <span class="text-sm ml-1">${formatMessageContent(newReply.content)}</span>
                                    </div>
                                    <div class="flex items-center mt-1">
                                        <span class="text-xs text-gray-500">刚刚</span>
                                        <button class="delete-comment ml-3 text-xs text-red-500" data-id="${newReply.id}">删除</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                    repliesContainer.insertAdjacentHTML('afterbegin', replyHtml);
                    replyInput.classList.add('hidden');
                    textarea.value = '';
                });
        } else {
            showNotification('回复失败: ' + (data.message || ''), 'error');
        }
    })
    .catch(error => {
        console.error('发送回复失败:', error);
        showNotification('发送回复失败', 'error');
    })
    .finally(() => {
        // 恢复按钮状态
        btn.disabled = false;
        btn.classList.remove('btn-disabled');
        btn.textContent = '发送';
    });
}

// 发送评论
function sendComment() {
    const postId = document.getElementById('commentPostId').value;
    const content = document.getElementById('commentContent').value.trim();
    const sendBtn = document.getElementById('sendComment');

    // 验证内容和状态
    if (!postId || !content) {
        showNotification('评论内容不能为空', 'error');
        return;
    }

    // 防止重复提交：禁用按钮并显示加载状态
    sendBtn.disabled = true;
    sendBtn.classList.add('btn-disabled');
    sendBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>发送中...';

    fetch(`/api/posts/${postId}/comments`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content })
    })
    .then(res => res.json())
    .then(data => {
        if (data.status === 'success') {
            showNotification('评论成功', 'success');
            document.getElementById('commentContent').value = '';

            // 获取新评论并添加到列表
            fetch(`/api/comments/${data.comment_id}`)
                .then(res => res.json())
                .then(newComment => {
                    const commentsList = document.getElementById('commentsList');
                    if (commentsList.querySelector('.text-center')) {
                        commentsList.innerHTML = '';
                    }
                    const commentEl = createCommentElement(newComment);
                    commentsList.prepend(commentEl);
                    // 确保事件委托有效
                    commentsList.addEventListener('click', handleCommentEvents);
                });
        } else {
            showNotification('评论失败: ' + (data.message || ''), 'error');
        }
    })
    .catch(error => {
        console.error('发送评论失败:', error);
        showNotification('发送评论失败', 'error');
    })
    .finally(() => {
        // 无论成功失败，都恢复按钮状态
        sendBtn.disabled = false;
        sendBtn.classList.remove('btn-disabled');
        sendBtn.innerHTML = '<i class="fa fa-comment mr-2"></i>发送评论';
    });
}

// 显示通知
function showNotification(message, type) {
    const notification = document.getElementById('notification');
    const icon = document.getElementById('notificationIcon');
    const messageEl = document.getElementById('notificationMessage');

    if (!notification || !icon || !messageEl) return;

    // 设置通知类型样式
    if (type === 'success') {
        notification.className = 'fixed bottom-4 right-4 px-6 py-3 bg-green-50 text-green-700 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50';
        icon.className = 'fa fa-check-circle mr-2';
    } else {
        notification.className = 'fixed bottom-4 right-4 px-6 py-3 bg-red-50 text-red-700 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50';
        icon.className = 'fa fa-exclamation-circle mr-2';
    }

    // 设置消息内容并显示
    messageEl.textContent = message;
    notification.classList.remove('translate-y-20', 'opacity-0');
    notification.classList.add('translate-y-0', 'opacity-100');

    // 3秒后隐藏
    setTimeout(() => {
        notification.classList.remove('translate-y-0', 'opacity-100');
        notification.classList.add('translate-y-20', 'opacity-0');
    }, 3000);
}

// 格式化时间显示
function formatTime(isoTime) {
    const date = new Date(isoTime);
    const now = new Date();
    const diffMs = now - date;
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMins / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffMins < 1) {
        return '刚刚';
    } else if (diffMins < 60) {
        return `${diffMins}分钟前`;
    } else if (diffHours < 24) {
        return `${diffHours}小时前`;
    } else if (diffDays < 7) {
        return `${diffDays}天前`;
    } else {
        return `${date.getMonth() + 1}月${date.getDate()}日`;
    }
}

// 格式化消息内容（处理换行）
function formatMessageContent(content) {
    return content
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;')
        .replace(/\n/g, '<br>');
}


</script>
</body>
</html>